const App = getApp()
const db = wx.cloud.database()
const _ = db.command
// 监听器
let watcher
let that
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 实践任务详情
    practiceDetails: "",
    // 下载弹窗
    modalName: "",
    // 剩余时间、未开始时间、状态时间
    stateYime: 30 * 60 * 60 * 1000,
    practiceState: "",
    // 下载回来的文件链接地址
    downloadFilePath: "",
    // 按钮loading
    btnloading: false,
    // 显示fab
    fabShow: false,
    // 笼罩层
    overlayShow: false,
    // 详细描述输入框高度
    inputHeight: {
      minHeight: 70
    },
    setlist: {
      name: "",
      describe: "",
      addtime: null,
      endtime: null,
      list: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this
    let practiceId = JSON.parse(decodeURIComponent(options.passData));
    console.log('传值后', practiceId);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      practiceId: practiceId,
      UserInfo: UserInfo
    })
    // 实时数据推送
    App.toast.showLoading('加载中')
    watcher = db.collection('practice')
      .where({
        practiceId: that.data.practiceId
      }).watch({
        onChange: this.onChange.bind(this),
        onError: function (err) {
          console.error(err)
        }
      })

  },
  // 监听器
  onChange(snapshot) {
    App.toast.hideLoading()
    console.log('is init data', snapshot.type === 'init')
    console.log(snapshot);
    if (snapshot.type === 'init') {
      let list = snapshot.docs[0]
      console.log('获取实践任务详情', list);
      that.setData({
        practiceDetails: list,
        ['setlist.list']: list.file,
      })
      // 获取倒计时
      let stateYime = null
      let practiceState = ""
      if (list.addtime - Date.now() >= 0 && list.practiceSwitch === false) {
        // 如果开始时间距离当前时间大于0，且实践任务没有开始，那就把剩余时间赋值给计时器，为0会自动开启
        stateYime = list.addtime - Date.now()
        practiceState = "尚未开始"
      } else if (list.practiceState === '提前终止') {
        // 如果实践任务状态是"提前终止",那就是人为的提前终止
        stateYime = null
        practiceState = "提前终止"
      } else if (list.addtime - Date.now() < 0 && list.endtime - Date.now() > 0) {
        // 因为实践任务一开始默认是关闭的，如果当前时间已经>开始时间<结束时间那就启动实践任务
        that.addTimeStartPractice()
        // 已读方法
        that.setRead()
        stateYime = list.endtime - Date.now()
        practiceState = "正在进行"
      } else {
        // 如果当前时间已经>结束时间，那就终止实践任务
        stateYime = null
        practiceState = "已经终止"
        that.EndTimeClosePractice()
      }
      console.log('stateYime', stateYime);
      console.log('practiceState', practiceState);
      that.setData({
        stateYime: stateYime,
        practiceState: practiceState
      })

    } else {
      let list = snapshot.docs[0]
      console.log('更新后的实践任务详情', list);
      if (!list) {
        console.log('没有数据');
        return
      }
      that.setData({
        practiceDetails: list,
        ['setlist.list']: list.file,
      })
      // 获取倒计时
      let stateYime = null
      let practiceState = ""
      if (list.addtime - Date.now() >= 0 && list.practiceSwitch === false) {
        // 如果开始时间距离当前时间大于0，且实践任务没有开始，那就把剩余时间赋值给计时器，为0会自动开启
        stateYime = list.addtime - Date.now()
        practiceState = "尚未开始"
      } else if (list.practiceState === '提前终止') {
        // 如果实践任务状态是"提前终止",那就是人为的提前终止
        stateYime = null
        practiceState = "提前终止"
      } else if (list.addtime - Date.now() < 0 && list.endtime - Date.now() > 0) {
        // 因为实践任务一开始默认是关闭的，如果当前时间已经>开始时间<结束时间那就启动实践任务
        that.addTimeStartPractice()
        // 已读方法
        that.setRead()
        stateYime = list.endtime - Date.now()
        practiceState = "正在进行"
      } else {
        // 如果当前时间已经>结束时间，那就终止实践任务
        stateYime = null
        practiceState = "已经终止"
        that.EndTimeClosePractice()
      }
      console.log('stateYime', stateYime);
      console.log('practiceState', practiceState);
      that.setData({
        stateYime: stateYime,
        practiceState: practiceState
      })

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    watcher.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },



  // 关闭提示弹窗
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // fab
  fabShow() {
    that.setData({
      overlayShow: !that.data.overlayShow,
      fabShow: !that.data.fabShow
    });
  },
  // 关闭fab和笼罩层
  onClickHide() {
    that.setData({
      overlayShow: false,
      fabShow: false
    });
  },


  // 将未读状态改成已读
  setRead() {
    let practiceDetails = that.data.practiceDetails
    console.log('practiceDetails', practiceDetails);
    let newUser = practiceDetails.courseMember.filter(item => {
      return that.data.UserInfo.account === item.account && item.Read === false
    })
    console.log('newUser', newUser);
    if (newUser.length === 0) {
      console.log('已经阅读了');
      return false
    }
    db.collection('practice').where(_.and([{
      practiceId: that.data.practiceDetails.practiceId
    }, {
      'courseMember.account': _.in([that.data.UserInfo.account])
    }])).update({
      data: {
        'courseMember.$.Read': true,
      },
      success: function (res) {
        console.log('更新成功');
      }
    })
  },

  // 下载文件到本地
  downloadFile(e) {
    let fileid = e.currentTarget.dataset.fileid
    App.toast.showLoading('下载中')
    wx.cloud.getTempFileURL({
      fileList: [{
        fileID: fileid,
      }]
    }).then(res => {
      App.toast.hideLoading()
      console.log('返回来的链接', res.fileList[0])
      that.setData({
        modalName: "DialogModal1",
        downloadFilePath: res.fileList[0].tempFileURL,
      })
    }).catch(error => {
      console.error(error)
    })
  },
  // 复制文件链接地址
  codeFilePath(e) {
    console.log(e.currentTarget.dataset);
    let filepath = e.currentTarget.dataset.filepath
    wx.setClipboardData({
      data: filepath,
      success: res => {
        console.log(res);
        App.toast.showToast('地址已经复制', 'none', 1000)
        that.hideModal()
      }
    })
  },

  // 预览照片
  previewImage(e) {
    console.log('预览', e.currentTarget.dataset.imgpath);
    let url = e.currentTarget.dataset.imgpath;
    wx.previewImage({
      current: url,
      urls: [url]
    })
  },

  // 提交实践任务
  submit(e) {
    let practiceId = e.currentTarget.dataset.practiceid
    console.log(practiceId);
    App.route.navTo('/pages/students/practice/submit/index', practiceId)
  },
  // 实践任务开始时间已到，应该启动任务
  addTimeStartPractice() {
    if (that.data.practiceDetails.practiceSwitch === true) {
      console.log('实践任务已经开始了');
      return
    }
    db.collection('practice').where({
      practiceId: that.data.practiceDetails.practiceId
    }).update({
      data: {
        practiceSwitch: true,
        practiceState: "正在运行"
      },
      success: function (res) {
        console.log('实践任务已经启动', res);
      }
    })
  },
  // 实践任务结束时间已到，应该终止任务
  EndTimeClosePractice() {
    if (that.data.practiceDetails.practiceSwitch === false) {
      console.log('实践任务已经终止了');
      return
    }
    db.collection('practice').where({
      practiceId: that.data.practiceDetails.practiceId
    }).update({
      data: {
        practiceSwitch: false,
        practiceState: "已经终止"
      },
      success: function (res) {
        console.log('已经终止', res);
        App.toast.showToast('实践任务时间已截止,正在终止实践任务')
      }
    })
  },
  // 仅允许学生查看自己的实践任务详情
  memberPractice(e) {
    let data = e.currentTarget.dataset
    if (that.data.UserInfo.account === data.id) {
      App.route.navTo('/pages/teachers/practice/memberPractice/index', data)
    }
  }
})